package com.fly.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.fly.constant.RedisConstant;
import com.fly.dao.SetmealDao;
import com.fly.entity.PageResult;
import com.fly.entity.QueryPageBean;
import com.fly.pojo.CheckGroup;
import com.fly.pojo.Setmeal;
import com.fly.service.SetmealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    //使用JedisPool操作Redis服务
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private SetmealDao setmealDao;
    //新增套餐
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        //新增套餐,操作t_setmeal表
       setmealDao.add(setmeal);

       //设置套餐和检查组的关系,操作t_setmeal_checkgroup表
        //获取新增套餐的id
        Integer isetmealId = setmeal.getId();
        this.setSetmealAndCheckgroup(checkgroupIds,isetmealId);

        //将保存数据库的图片名称保存在redis集合中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
    }

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {

        Integer pageSize = queryPageBean.getPageSize();//每页记录数
        String queryString = queryPageBean.getQueryString();//查询条件
        Integer currentPage = queryPageBean.getCurrentPage();//当前页

        //完成分页查询,基于mybatis提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        //条件查询
        Page<CheckGroup> page =setmealDao.findByCondition(queryString);
        //获取总记录数
        long total = page.getTotal();
        //查询的数据
        List<CheckGroup> rows = page.getResult();

        return new PageResult(total,rows);

    }


    //建立套餐与检查组的多对多关系
    private void setSetmealAndCheckgroup (Integer[] checkgroupIds, Integer setmealId){
        //将检查组的id和检查项的id存储t_checkgroup_checkitem表中
        if (checkgroupIds!=null && checkgroupIds.length>0){
            //遍历每一个检查项的id,和检查组的id存储到t_checkgroup_checkitem
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map =new HashMap<>();
                map.put("checkgroupId",checkgroupId);
                map.put("setmealId",setmealId);
                setmealDao.setSetmealAndCheckgroup(map);
            }
        }
    }
}